/*******************************************************************************
 * tuannh ********* function : load map, insert - edit - delete feature
 ******************************************************************************/
var map;
var ctrl_Layer;
var ctrl_OV;
var untiled;
var tiled;
var pureCoverage = false;
var format_SLD = new OpenLayers.Format.SLD();
// pink tile avoidance
OpenLayers.IMAGE_RELOAD_ATTEMPTS = 5;
// make OL compute scale according to WMS spec
OpenLayers.DOTS_PER_INCH = 25.4 / 0.28;
// avoid pink tiles
OpenLayers.Util.onImageLoadErrorColor = "transparent";
var colorSelected = "#ff0000";
var colorUnSelected = "#336699";
var ctrlSelectFeatures = null;
var ctrlPanelEditting = null;
var pan_map = null;
var clickEvent = null;
var split = null;
var navExtent = null;
var feature_Current_Action = null;
var numBaseLayer = 0; // 0: lay base map tu file config - 1: lay base map tu goole map
// vector Quan/Huyen - Phuong/Xa
var vectorDistricts = null, vectorCommune = null;

OpenLayers.Control.Click = OpenLayers.Class(OpenLayers.Control, {
	defaultHandlerOptions : {
		'single' : true,
		'double' : false,
		'pixelTolerance' : 0,
		'stopSingle' : false,
		'stopDouble' : false
	},

	initialize : function(options) {
		this.handlerOptions = OpenLayers.Util.extend({},
				this.defaultHandlerOptions);
		OpenLayers.Control.prototype.initialize.apply(this, arguments);
		this.handler = new OpenLayers.Handler.Click(this, {
			'click' : this.onClick,
			'dblclick' : this.onDblclick
		}, this.handlerOptions);
	},

	onClick : clickEvent_ModifyFeature,

	onDblclick : dbclickEvent_ModifyFeature
});

var DeleteFeature = OpenLayers.Class(
				OpenLayers.Control,
				{
					initialize : function(layer, options) {
						OpenLayers.Control.prototype.initialize.apply(this,
								[ options ]);
						this.layer = layer;
						this.handler = new OpenLayers.Control.SelectFeature(
								this.layer, {
									clickout : true,
									toggle : false,
									multiple : false,
									hover : false,
									toggleKey : "ctrlKey", // ctrl key removes
									// from selection
									multipleKey : "shiftKey", // shift key
									// adds to
									// selection
									box : isDrawBox,
									onSelect : this.selectedFeature
								});
					},
					selectedFeature : function(feature) {
						this.deactivate();
						if (index_Feature_Del > 0)
							featureUnSelected(feature_Delete[index_Feature_Del - 1]);
						else {
							// an feature da xoa
							var i = 0;
							var indexLayer = _select_Tool_cboLayers[_select_Tool_cboLayers.selectedIndex].value;
							for (i = 0; i < this.map.layers[indexLayer].features.length; i++) {
								if (this.map.layers[indexLayer].features[i].state == OpenLayers.State.DELETE) {
									this.map.layers[indexLayer]
											.drawFeature(
													this.map.layers[indexLayer].features[i],
													'after_delete');
								}
							}
						}
						feature_Delete.push(feature);
						featureSelected(feature_Delete[index_Feature_Del]);
						index_Feature_Del++;
					},
					setMap : function(map) {
						this.handler.setMap(map);
						OpenLayers.Control.prototype.setMap.apply(this,
								arguments);
					},
					CLASS_NAME : "OpenLayers.Control.DeleteFeature"
				});

function clickMap(param) {
	// Delete Feature
	if (Action_Current == Portlet_Type_Action.Delete) {
		if (!click_Map_Delete)
			return;
		// if(map.div.mousedown(function(e){
		var indexLayer = _select_Tool_cboLayers[_select_Tool_cboLayers.selectedIndex].value;
		indexLayer = indexLayer - 1 - map_WMS.length;

		if (feature_Delete.length > 0) {
			featureSelected(feature_Delete[index_Feature_Del - 1]);
			var answer = true;
			if (isConfirm)
				answer = confirm("Bạn có muốn xóa không?");
			if (answer) {
				bSaveEditting = false;
				featureRemove(feature_Delete[index_Feature_Del - 1]);
				feature_Delete.splice(index_Feature_Del - 1, 1);
				index_Feature_Del = index_Feature_Del - 1;
				alert("Xóa thành công!");
				if (index_Feature_Del > 0)
					featureSelected(feature_Delete[index_Feature_Del - 1]);
			} else {
				featureUnSelected(feature_Delete[index_Feature_Del - 1]);
				// feature_Delete.splice(index_Feature_Del, 1);
			}
			if (feature_Delete.length == 0) {
				Del_Obj[indexLayer].handler.activate();
			}
			// else featureSelected(feature_Delete[index_Feature_Del-1]);
		} else
			Del_Obj[indexLayer].handler.activate();
	}
}

function preFeatureInsert(feature) {
}

function endBox_Feature(end) {
}

function featureSelected(feature) {
	var indexLayer = _select_Tool_cboLayers[_select_Tool_cboLayers.selectedIndex].value;
	map.layers[indexLayer].drawFeature(feature, "delete_selection");
}

function featureUnSelected(feature) {
	var indexLayer = _select_Tool_cboLayers[_select_Tool_cboLayers.selectedIndex].value;
	map.layers[indexLayer].drawFeature(feature, "select");
}

function featureRemove(feature) {
	var indexLayer = _select_Tool_cboLayers[_select_Tool_cboLayers.selectedIndex].value;

	if (feature.fid == undefined) {
		map.layers[indexLayer].destroyFeatures([ feature ]);
	} else {
		feature.state = OpenLayers.State.DELETE;
		map.layers[indexLayer].events.triggerEvent("afterfeaturemodified", {
			feature : feature
		});
		feature.renderIntent = "select";
		map.layers[indexLayer].drawFeature(feature, 'after_delete');
	}
}

function featureUpdate(feature) {
	var indexLayer = _select_Tool_cboLayers[_select_Tool_cboLayers.selectedIndex].value;

	if (feature.fid == undefined) {
	} else {
		feature.state = OpenLayers.State.UPDATE;
		map.layers[indexLayer].events.triggerEvent("afterfeaturemodified", {
			feature : feature
		});
		feature.renderIntent = "select";
		map.layers[indexLayer].drawFeature(feature, 'default');
	}
}

function notice(bounds) {
	// areaSelected(bounds);
}

var timeoutGetFeature = null;
var arrFeature_District = null, arrFeature_Commune = null;
function getFeatures_District_Commune()
{
	if(vectorDistricts.features.length==0)
	{
		timeoutGetFeature = setTimeout("getFeatures_District_Commune();", 3000);
	}
	else
	{
		arrFeature_District = vectorDistricts.features;
		arrFeature_Commune = vectorCommune.features;
		vectorDistricts.setVisibility(false);
		vectorCommune.setVisibility(false);
		clearTimeout(timeoutGetFeature);
	}
}

/** ********* LOAD MAP ************* */
function init(divMap) {
	initial();
	// OpenLayers.ProxyHost = "/geoserver/cgi-bin/proxy.cgi?url=";
	OpenLayers.ImgPath = l_img_path_openlayer; //"http://192.168.1.29:8080/OpenLayers/img/";
	OpenLayers.ProxyHost = "/cgi-bin/proxy.cgi?url=";

	// if this is just a coverage or a group of them, disable a few items,
	// and default to png format
	format = 'image/png';

	var defStyle = {
		strokeColor : colorUnSelected,
		strokeOpacity : "0.7",
		strokeWidth : 2,
		fillColor : colorUnSelected,
		pointRadius : 3,
		cursor : "pointer"
	};
	var sty = OpenLayers.Util.applyDefaults(defStyle,
			OpenLayers.Feature.Vector.style["default"]);
	var sm = new OpenLayers.StyleMap({
		'default' : sty,
		'select' : {
			strokeColor : colorSelected,
			fillColor : colorSelected
		}
	});

	// set up projections
	// World Geodetic System 1984 projection
	var WGS_Projection = new OpenLayers.Projection(Projection);
	var WGS84 = new OpenLayers.Projection("EPSG:4326");
	// WGS84 Google Mercator projection
	var WGS84_google_mercator = new OpenLayers.Projection("EPSG:900913");

	//OpenLayers.Projection.addTransform("EPSG:3405", "EPSG:900913", OpenLayers.Projection.nullTransform);
	var bounds = new OpenLayers.Bounds(XMin, YMin, XMax, YMax).transform(WGS_Projection, WGS_Projection);

	// roundedCornerColor
	var ctrl_LayerSwitcher = new OpenLayers.Control.LayerSwitcher();
	ctrl_LayerSwitcher.roundedCornerColor = "lavender";
	var options = {
		controls : [ new OpenLayers.Control.Navigation(),
				new OpenLayers.Control.PanZoomBar({
					position : new OpenLayers.Pixel(2, 5)
				}) ],
		maxExtent: bounds,
		maxResolution: 180.968994140625,
		projection : WGS_Projection,
		//displayProjection : WGS84_google_mercator,
		units : 'm'
	};
	map = new OpenLayers.Map(divMap, options);
	
	
	// /*********************************************************
	// WMS - WFS
	// /*********************************************************

	var isBaseMap = false;
	var vector = null, vector_Item = null;
	var snap = null;
	var draw = null, drawMode = null;
	var modify = null;
	var del = null, delVertice = null;
	var divObj = null, aObj = null, inputObj = null;

	var i = 0;
	// IndexLayer|Layer_Name|StyleMap|Projection|SaveObj|Version|URL|Feature_Type|Feature_NS|Geometry_Name|Geometry_Type|DisplayClass_Draw|DisplayClass_Modify|DisplayClass_Del
	// map service
	bError_Editting = new Array();
	for (i = 0; i < Vector_Array.length; i++) {
		bError_Editting[i] = false;
		vector_Item = Vector_Array[i];
		if (!vector_Item.Map_Service)
			continue;
		if(vector_Item.Base_Map)
		{
			isBaseMap = true;
			_getElementById("div_Map_BaseMap_Gogle").style.display = "none";
			_getElementById("div_Map_BaseMap").style.display = "block";
			_getElementById("span_Map_LayerBase_User").innerHTML = vector_Item.Layer_Name;
		}
		projection = vector_Item.Projection;
		tiled = new OpenLayers.Layer.WMS(
				vector_Item.Layer_Name,
				vector_Item.URL,
				{
					LAYERS : vector_Item.Feature_NS + ':' + vector_Item.LayerId,
					STYLES : '',
					format : format,
					transparent : true,
					tiled : false,
					tilesOrigin : map.maxExtent.left + ','
							+ map.maxExtent.bottom
				}, {
					buffer : 0,
					displayOutsideMaxExtent : true,
					isBaseLayer : vector_Item.Base_Map,
					singleTile : true,
					yx : {
						'EPSG:4326' : true
					}
				});
		tiled.visibility = vector_Item.Visible;
		map.addLayer(tiled);
		//vector_Item.IndexLayer = map.layers.length; // chi dung truong hop lay base map tu CSDL
	}
	if(!isBaseMap)
	{
		numBaseLayer = 1;
		var googlemap = new OpenLayers.Layer.Google("Google Streets", {
			numZoomLevels : 20
		});
		map.addLayer(googlemap);
		map.setLayerIndex(googlemap, 0);
	}
	
	// feature service
	var saveObj = null;
	for (i = 0; i < Vector_Array.length; i++) {
		vector_Item = Vector_Array[i];
		if (vector_Item.Map_Service)
			continue;
		// vector		
		saveObj = vector_Item.SaveObj;

		vector = new OpenLayers.Layer.Vector(vector_Item.Layer_Name, {
			styleMap : vector_Item.StyleMap,
			projection : new OpenLayers.Projection(vector_Item.Projection),
			strategies : [ new OpenLayers.Strategy.BBOX(), saveObj ],
			protocol : new OpenLayers.Protocol.WFS({
				version : vector_Item.Version, // "1.0.0
				url : vector_Item.URL,
				featureType : vector_Item.Feature_Type,
				featureNS : vector_Item.Feature_NS,
				geometryName : vector_Item.Geometry_Name
			})
		});

		// alert("vector_Item.Geometry_Name: " + vector_Item.Geometry_Name);
		vector.IndexLayer = vector_Item.IndexLayer;
		vector.setVisibility(vector_Item.Visible);
		vector.events.on({
			'beforefeaturemodified' : function(evt) {
				feature_Current_Action = evt.feature;
			},
			'afterfeaturemodified' : function(evt) {
				// feature_Current_Action = null;
			}
		});
		Vector_Obj[Vector_Obj.length] = vector;
		Save_Obj[Save_Obj.length] = saveObj;

		switch(vector_Item.LayerId.toLowerCase())
		{
		case "dwb_district":
			vectorDistricts = vector;
			break;
		case "dwb_commune":
			vectorCommune = vector;
			break;
		}
		if(vector_Item.Display) 
			map.addLayer(vector);
		else
			map.addLayer(vector);
		//vector_Item.IndexLayer = map.layers.length; // chi dung truong hop lay base map tu CSD
	}

	// add layers
	/*for (i = 0; i < Vector_Obj.length; i++) {
		map.addLayer(Vector_Obj[i]);
		vector_Item.IndexLayer = map.layers.length; // chi dung truong hop lay base map tu CSDL
	}*/

	vectorGraphics = new OpenLayers.Layer.Vector("Graphic", {
		styleMap : sm_Line
	});

	vectorGraphics_Vertex = new OpenLayers.Layer.Vector("Graphic Vertex", {
		styleMap : sm_Measure
	});
	vectorGraphics1 = new OpenLayers.Layer.Vector("Graphic Zoom", {
	});
	map.addLayer(vectorGraphics);	
	map.addLayer(vectorGraphics_Vertex);
	map.addLayers(vectorGraphics1);
	
	map.events.register('click', map, clickMap);
	map.div.onmouseup = function(e) {
		var indexLayer = _select_Tool_cboLayers[_select_Tool_cboLayers.selectedIndex].value;
		switch (Action_Current) {
		case Portlet_Type_Action.Delete:
			if (!click_Map_Delete) {
				return false;
			}
			if (OpenLayers.Event.isRightClick(event)) {
				index_Feature_Del = index_Feature_Del - 1;
				if ((index_Feature_Del <= 0) && (feature_Delete.length > 0)) {
					featureUnSelected(feature_Delete[0]);
					index_Feature_Del = feature_Delete.length;
				} else if ((index_Feature_Del < feature_Delete.length)
						&& (index_Feature_Del > 0))
					featureUnSelected(feature_Delete[index_Feature_Del]);
				if (index_Feature_Del > 0)
					featureSelected(feature_Delete[index_Feature_Del - 1]);
				else {
					for (i = 0; i < feature_Delete.length; i++) {
						map.layers[indexLayer].drawFeature(feature, "default");
					}
					index_Feature_Del = 0;
					feature_Delete = new Array();
					indexLayer = _select_Tool_cboLayers[_select_Tool_cboLayers.selectedIndex].value;
					indexLayer = indexLayer - 1 - map_WMS.length;
					Del_Obj[indexLayer].handler.activate();
				}
			}
			break;
		case Portlet_Type_Action.Insert:
			// case General.AddPolyline_Action:
			// case General.AddPolygon_Action:
			/*
			 * if (OpenLayers.Event.isRightClick(event)) { Draw_Obj[indexLayer -
			 * 1].undo(); }
			 */
			break;
		/*
		 * case General.AddPoint_Action: var layer = Vector_Obj[indexLayer - 1];
		 * if (OpenLayers.Event.isRightClick(event)) {
		 * layer.destroyFeatures(layer.features[layer.features.length - 1]); }
		 * break;
		 */
		case Portlet_Type_Action.Del_Vertext:
			if (OpenLayers.Event.isRightClick(event)) {
				var indexLayer = _select_Tool_cboLayers[_select_Tool_cboLayers.selectedIndex].value;
				indexLayer = indexLayer - 1 - map_WMS.length;
				var delVertice = DelVertices_Obj[indexLayer];
				if (delVertice.removeControl.feature != null) {
					var answer = confirm("Bạn có muốn xóa điểm này không?");
					if (answer)// == true)
					{
						delVertice.removeControl.remove(delVertice.removeControl.feature);
					} else {
						delVertice.unSelect_Vertex(delVertice.removeControl.feature);
						// delVertice.removeControl.onUnselect(delVertice.removeControl.feature);
					}
				}
			}
			break;
		}
	};

	window.document.onkeydown = function(e) {
		var charCode = (event.which) ? event.which : event.keyCode;
		// alert(charCode);
		if (charCode == 116) // F5
		{
			window.location.reload();
			return false;
		}

		/*
		 * if ((Action_Current == General.Parallel_Line) || (Action_Current ==
		 * General.Perpendicular_Line) || (Action_Current ==
		 * General.DirectionLength_Line)) { var indexLayer =
		 * _select_Tool_cboLayers[_select_Tool_cboLayers.selectedIndex].value;
		 * if (charCode == 27) // ESC { _begin_Draw = false; bUndo_First = true;
		 * Draw_Obj[indexLayer - 1].undo(); } }
		 */
		if (Action_Current == Portlet_Type_Action.Delete) {
			if (!click_Map_Delete)
				return true;
			if (charCode == 27) // ESC
			{
				var indexLayer = _select_Tool_cboLayers[_select_Tool_cboLayers.selectedIndex].value;
				for (i = 0; i < feature_Delete.length; i++) {
					map.layers[indexLayer].drawFeature(feature_Delete[i],
							"default");
				}
				// cap nhat lai index cua doi tuong del
				index_Feature_Del = 0;
				feature_Delete = new Array();
				indexLayer = indexLayer - 1 - map_WMS.length;
				Del_Obj[indexLayer].handler.activate();
				return false;
			}
		}
		if (Action_Current == Portlet_Type_Action.Edit) {
			if (charCode == 27) // ESC
			{
				var indexLayer = _select_Tool_cboLayers[_select_Tool_cboLayers.selectedIndex].value;
				var layer_Activate = map.layers[indexLayer];
				if (feature_Current_Action != null)
					layer_Activate.drawFeature(feature_Current_Action, "default");
				feature_Current_Action = null;
				AddFeature_Attribute_Close();
				MapAction.Click_Action(true);
			}
		}
		return true;
	};

	// build up all controls
	// ctrl_Layer = new OpenLayers.Control.LayerSwitcher({ "div":
	// OpenLayers.Util.getElement('LayerList') });
	// map.addControl(ctrl_Layer);
	ctrl_OV = new OpenLayers.Control.OverviewMap({
		"div" : OpenLayers.Util.getElement('OV')
	});
	map.addControl(ctrl_OV);
	var scale = new OpenLayers.Control.ScaleLine({
		"div" : OpenLayers.Util.getElement('scale')
	});
	map.addControl(scale);
	var mousePosition = new OpenLayers.Control.MousePosition({
		element : _getElementById('location')
	});
	mousePosition.numDigits = 2;
	mousePosition.prefix = "X = ";
	mousePosition.separator = ", Y = ";
	// mousePosition.emptyString = "";
	map.addControl(mousePosition);
	map.zoomToExtent(bounds);

	// /***************** EDIT DATA **********************/
	var index_VextorLayer = 0;

	var controls_Vector = new Array();
	for (i = 0; i < Vector_Obj.length; i++) {
		controls_Vector[i] = Vector_Obj[i];
	}

	// add some editing tools to a panel
	ctrlPanelEditting = new OpenLayers.Control.Panel({
		displayClass : "customEditingToolbar_Visible"
	});

	for (i = 0; i < Vector_Array.length; i++) {
		vector_Item = Vector_Array[i];
		if (vector_Item.Map_Service)
			continue;
		// snap
		snap = new OpenLayers.Control.Snapping({
			layer : Vector_Obj[index_VextorLayer],
			targets : controls_Vector,
			greedy : false
		});
		snap.activate();
		Snap_Obj[Snap_Obj.length] = snap;
		// init snap
		for ( var j = 0; j < snap.targets.length; j++) {
			snap.targets[j].node = Snap_Array[j].Node;
			snap.targets[j].nodeTolerance = Snap_Array[j].Tolerance;
			;
			snap.targets[j].vertex = Snap_Array[j].Vertex;
			snap.targets[j].vertexTolerance = Snap_Array[j].Tolerance;
			snap.targets[j].edge = Snap_Array[j].Edge;
			snap.targets[j].edgeTolerance = Snap_Array[j].Tolerance;
		}

		drawMode = OpenLayers.Handler.Point;

		if (vector_Item.Geometry_Type == 'point') {
			drawMode = OpenLayers.Handler.Point;
			draw = new OpenLayers.Control.DrawFeature(
					Vector_Obj[index_VextorLayer], OpenLayers.Handler.Point, {
						displayClass : vector_Item.DisplayClass_Draw,
						title : "Draw " + vector_Item.Layer_Name,
						handlerOptions : {
							holeModifier : "altKey"
						}
					});
		} else if (vector_Item.Geometry_Type == 'polyline') {
			drawMode = OpenLayers.Handler.Path;
			draw = new OpenLayers.Control.DrawFeature(
					Vector_Obj[index_VextorLayer], OpenLayers.Handler.Path, {
						displayClass : vector_Item.DisplayClass_Draw,
						title : "Draw " + vector_Item.Layer_Name,
						multi : true,
						callbacks : {
							"point" : pointHandler_Path
						},
						handlerOptions : {
							holeModifier : "altKey"
						}
					});
		} else if (vector_Item.Geometry_Type == 'polygon') {
			drawMode = OpenLayers.Handler.Polygon;
			draw = new OpenLayers.Control.DrawFeature(
					Vector_Obj[index_VextorLayer], OpenLayers.Handler.Polygon,
					{
						displayClass : vector_Item.DisplayClass_Draw,
						title : "Draw " + vector_Item.Layer_Name,
						multi : true,
						handlerOptions : {
							holeModifier : "altKey"
						}
					});
		}

		// modify
		modify = new OpenLayers.Control.ModifyFeature(
				Vector_Obj[index_VextorLayer], {
					displayClass : vector_Item.DisplayClass_Modify,
					title : "Modify " + vector_Item.Layer_Name
				});
		//modify.createVertices = false;
		// delete
		del = new DeleteFeature(Vector_Obj[index_VextorLayer], {
			displayClass : vector_Item.DisplayClass_Del,
			title : "Delete " + vector_Item.Layer_Name
		});
		// del vertice
		delVertice = new OpenLayers.Control.DeleteVertex(
				Vector_Obj[index_VextorLayer], vectorGraphics_Vertex, {
					'displayClass' : 'olControlDeleteVertex',
					onModificationStart : onModificationStart,
					onModification : onModification,
					onModificationEnd : onModificationEnd
				});

		// draw
		Draw_Obj[Draw_Obj.length] = draw;
		draw.events.register('featureadded', draw, event_featureadded);
		// modify
		Modify_Obj[Modify_Obj.length] = modify;
		// del
		Del_Obj[Del_Obj.length] = del;
		DelVertices_Obj[DelVertices_Obj.length] = delVertice;

		index_VextorLayer++;
	}

	/*  binh */

	draw_Zoom = new OpenLayers.Control.DrawFeature(vectorGraphics1,
            OpenLayers.Handler.RegularPolygon, {
		        handlerOptions: {
		            sides: 4,
		            irregular: true
		        }
		    });
	draw_Zoom.events.register('featureadded', draw, event_featureadded_zomm);
	map.addControl(draw_Zoom);
	
	/******/

	
	var save = new OpenLayers.Control.Button({
		title : "Save Changes",
		trigger : function() {
			/*
			 * for(i=0;i<Save_Obj.length;i++) { Save_Obj[i].save(); }
			 */
			alert(Save_Obj.length + "\n saved...");
		},
		displayClass : "olControlSaveFeatures"
	});

	pan_map = new OpenLayers.Control.Navigation({
		title : "Navigate"
	});
	var controls_Toolbar = new Array();
	controls_Toolbar[controls_Toolbar.length] = pan_map;
	for (i = 0; i < Draw_Obj.length; i++) {
		controls_Toolbar[controls_Toolbar.length] = Draw_Obj[i];
	}
	for (i = 0; i < Modify_Obj.length; i++) {
		controls_Toolbar[controls_Toolbar.length] = Modify_Obj[i];
	}
	for (i = 0; i < Del_Obj.length; i++) {
		controls_Toolbar[controls_Toolbar.length] = Del_Obj[i];
	}
	for (i = 0; i < DelVertices_Obj.length; i++) {
		controls_Toolbar[controls_Toolbar.length] = DelVertices_Obj[i];
	}
	controls_Toolbar[controls_Toolbar.length] = save;
	ctrlPanelEditting.addControls(controls_Toolbar);

	tdToolbarEditting = document.getElementById('tdToolbarEditting');
	map.addControl(ctrlPanelEditting);
	pan_map.activate();

	clickEvent = new OpenLayers.Control.Click({
		handlerOptions : {
			"single" : true,
			"double" : true
		}
	});
	map.addControl(clickEvent);

	split = new OpenLayers.Control.Split({
		layer : null,
		eventListeners : {
			aftersplit : function(event) {
				flashFeatures(event.features);
			}
		}
	});
	map.addControl(split);

	// allow testing of specific renderers via "?renderer=Canvas", etc
	var renderer = OpenLayers.Util.getParameters(window.location.href).renderer;
	renderer = (renderer) ? [ renderer ]
			: OpenLayers.Layer.Vector.prototype.renderers;
	measureControls = {
		point : new OpenLayers.Control.Measure(OpenLayers.Handler.Point, {
			persist : true,
			handlerOptions : {
				layerOptions : {
					renderers : renderer,
					styleMap : sm_Measure
				}
			}
		}),
		line : new OpenLayers.Control.Measure(OpenLayers.Handler.Path, {
			persist : true,
			handlerOptions : {
				layerOptions : {
					renderers : renderer,
					styleMap : sm_Measure
				}
			}
		}),
		polygon : new OpenLayers.Control.Measure(OpenLayers.Handler.Polygon, {
			persist : true,
			handlerOptions : {
				layerOptions : {
					renderers : renderer,
					styleMap : sm_Measure
				}
			}
		})
	};
	var control;
	for ( var key in measureControls) {
		control = measureControls[key];
		control.events.on({
			"measure" : handleMeasurements,
			"measurepartial" : handleMeasurements
		});
		map.addControl(control);
	}

	// parent control must be added to the map
	navExtent = new OpenLayers.Control.NavigationHistory();
	map.addControl(navExtent);

	// style default
	OpenLayers.Request.GET({
		url : sStyle_SLD,
		success : complete
	});
	extentChanged();
	getFeatures_District_Commune();
}

var bAction_BackExtent = false, bAction_NextExtent = false;
var objExtentTimeOut = null;
function extentChanged() {
	if (navExtent == null)
		return;
	if (navExtent.previousStack.length == 0) {
		objExtentTimeOut = setTimeout("extentChanged();", 1000);
	} else {
		clearTimeout(objExtentTimeOut);
		bAction_BackExtent = true;
		Portlet_Image.swapImg(p_eBackExtent.imgControl, true);
	}
}

// handler for the OpenLayers.Request.GET function in the init method
function complete(req) {
	sld = format_SLD.read(req.responseXML || req.responseText);
	setLayerStyles();
}

function setLayerStyles() {
	// set the default style for each layer from sld
	for ( var l in sld.namedLayers) {
		var styles = sld.namedLayers[l].userStyles;
		var style;
		for ( var i = 0, ii = styles.length; i < ii; ++i) {
			style = styles[i];
			for ( var j = 0; j < Vector_Array.length; j++) {
				if (Vector_Array[j].Map_Service)
					continue;
				if (l.toLowerCase() == Vector_Array[j].LayerId.toLowerCase()) {
					map.layers[Vector_Array[j].IndexLayer].styleMap.styles["default"] = style;
					break;
				}
			}
			/*
			 * if (style.isDefault) {
			 * map.getLayersByName(l)[0].styleMap.styles["default"] = style;
			 * break; }
			 */
		}
	}
}
/** ************ END LOAD MAP ***************** */

/** ********* General Function ************ */
function event_featureadded_zomm(evt)
{
	var feature= evt.feature;
	var bounds = feature.geometry.getBounds();
	map.zoomToExtent(bounds);
}
/** *************************************** */
/*
function event_featureadded_zoomOut(evt)
{
	var feature= evt.feature;
	var bounds = feature.geometry.getBounds();
	map.zoomToExtent(bounds);
}*/

/** **************** ADD *********************** */
function event_featureadded(evt) {
	if (Action_Current == Portlet_Type_Action.Insert
			|| Action_Current == Portlet_Type_Action.Add_Line_Extension) {
		feature_Current_Action = evt.feature;
		// _div_Map_divAddFeature_Attribute
		_div_Map_divAddFeature_Attribute.style.display = "block";
		var top = _div_Map_divToolbar.offsetTop + _div_Map_divToolbar.offsetHeight;
		var left = map_Left + map_Width - _div_Map_divAddFeature_Attribute.offsetWidth;
		_div_Map_divAddFeature_Attribute.style.top = (top + 5) + "px";
		_div_Map_divAddFeature_Attribute.style.left = (left - 5) + "px";
		_div_Map_divAddFeature_Attribute.innerHTML = "";
		var indexLayer = _select_Tool_cboLayers[_select_Tool_cboLayers.selectedIndex].value;
		if (arrField_Alias_Current.length == 0) {
			var sLayerID = Vector_Array[indexLayer - numBaseLayer].LayerId; // tru di base layer
			var i = 0;
			for (i = 0; i < arrField_Alias.length; i++) {
				if (trim(arrField_Alias[i].LayerName.toLowerCase()) == trim(sLayerID.toLowerCase())) {
					arrField_Alias_Current[arrField_Alias_Current.length] = arrField_Alias[i];
				}
			}
			arrField_Alias_Current.sort(function(a, b) {
				var x = a.Index - b.Index;
				return x;
			});
		}
		if (arrField_Alias_Current.length == 0) {
			alert("No attribute");
			if (Action_Current == Portlet_Type_Action.Insert)
				featureRemove(feature_Current_Action);
			_div_Map_divAddFeature_Attribute.style.display = "none";
			return;
		}
		bSaveEditting = false;
		Panel_Current.current_ImgAction.finish = false;
		MapAction.Edit_Action(true);
		indexLayer = indexLayer - 1 - map_WMS.length;
		Modify_Obj[indexLayer].mode == OpenLayers.Control.ModifyFeature.RESHAPE;
		Modify_Obj[indexLayer].selectFeature(feature_Current_Action);
		if (Panel_Current.current_ImgAction.divContainer != null)
			Panel_Current.current_ImgAction.divContainer.divChild = _div_Map_divAddFeature_Attribute;
		fillContructor_from_XML();
	}
}

function fillContructor_from_XML() {	
	removeChild_Div(_div_Map_divAddFeature_Attribute);
	// create table
	/* <table id="tbl_Map_AddFeature_Attribute" style="width:100%; margin:5px;"> */
	var objTable = document.createElement("table");
	objTable.id = "tbl_Map_AddFeature_Attribute";
	objTable.style.width = "100%";
	objTable.style.margin = "5px";
	/*
	 * <tr>
	 * <th id="th_Map_AddFeature_Attribute" style="font-weight: bold; font-style: italic;">
	 * <span id="span_Map_AddFeature_Attribute"></span> </th>
	 * <td colspan="1" align="right"> <img
	 * src="/PMap-portlet/html/pmap_portlet/img/cancel.png" onclick="return
	 * AddFeature_Attribute_Close();" style="cursor:pointer; padding: 0px 10px
	 * 0px 0px" /> </td> </tr> <tr> <td colspan="2"> <hr /> </td> </tr>
	 */
	var objTR = document.createElement("tr");
	var objTH = document.createElement("th");
	objTH.style.fontWeight = "bold";
	objTH.style.fontStyle = "italic";
	var objSpan = document.createElement("span");
	objSpan.id = "span_Map_AddFeature_Attribute";
	if (Action_Current == Portlet_Type_Action.Insert)
		objSpan.innerHTML += l_th_Map_AddFeature;
	else if (Action_Current == Portlet_Type_Action.Add_Line_Extension)
		objSpan.innerHTML += l_th_Map_AddFeature;
	else
		objSpan.innerHTML += l_th_Map_ModifyFeature;
	objTH.appendChild(objSpan);

	var objTD = document.createElement("td");
	objTD.colspan = "1";
	objTD.align = "right";
	var objImg = document.createElement("img");
	objImg.src = "/PMap-portlet/html/pmap_portlet/img/cancel.png";
	objImg.onclick = AddFeature_Attribute_Close;
	objImg.style.cursor = "pointer";
	objImg.style.padding = "0px 10px 0px 0px";
	objTD.appendChild(objImg);

	objTR.appendChild(objTH);
	objTR.appendChild(objTD);
	objTable.appendChild(objTR);

	var objTR_HR = document.createElement("tr");
	var objTD_HR = document.createElement("td");
	objTD_HR.colspan = "3";
	var objHR = document.createElement("hr");
	objTD_HR.appendChild(objHR);
	objTR_HR.appendChild(objTD_HR);
	objTable.appendChild(objTR_HR);

	var featureCurrent = null;
	if (arguments.length > 0)
		featureCurrent = feature_Current_Action = arguments[0];
	for ( var i = 0; i < arrField_Alias_Current.length; i++) {
		if (!arrField_Alias_Current[i].IsShow)
			continue;
		/*
		 * <tr> <td> Id_Code </td> <td> <input type="text"
		 * id="txt_Map_AddFeature_Attribute_IdCode" value="idcode" /> </td>
		 * </tr>
		 */
		var objTR_Alias = document.createElement("tr");
		var objTD_Title_Alias = document.createElement("td");
		objTD_Title_Alias.innerHTML = arrField_Alias_Current[i].Alias;
		var objTD_Text_Alias = document.createElement("td");
		var obj_Text_Alias = null;
		if(arrField_Alias_Current[i].Type == "date")
		{
			var input_Text_Alias = document.createElement("input");
			input_Text_Alias.type = "text";
			input_Text_Alias.style.width = "145px";
			input_Text_Alias.id = "date_Map_AddFeature_Attribute_" + arrField_Alias_Current[i].Name;
			$date = $(input_Text_Alias);
			$date.datepicker({
                numberOfMonths: 1,
                constrainInput: true,
                dateFormat: 'dd/mm/yy',
                showButtonPanel: false,
                hideIfNoPrevNext: true,
                autoSize: false,
                onSelect: function(date)
                {
                	alert(date);
                	var splitDate = date.split('/');
                	var dateUpdate = splitDate[1] + "/" + splitDate[0] + "/" + splitDate[2];
                	if (feature_Current_Action.feature) {
                		feature_Current_Action.feature.attributes[this.attribute] = dateUpdate;
                	} else {
                		feature_Current_Action.attributes[this.attribute] = dateUpdate;
                	}
                }
            });
			if (featureCurrent != null) 
			{
				var objValue = null;
				if (feature_Current_Action.feature) {
					objValue = feature_Current_Action.feature.attributes[arrField_Alias_Current[i].Name];
				} else {
					objValue = feature_Current_Action.attributes[arrField_Alias_Current[i].Name];
				}
				if (objValue != undefined)
				{
					
				}
			}
			else
			{
				var currentTime = new Date();
				$date.datepicker("setDate", currentTime.getDate() + "/" + (currentTime.getMonth() + 1) + "/" + currentTime.getFullYear());
			}
			input_Text_Alias.attribute = arrField_Alias_Current[i].Name;
			objTD_Text_Alias.appendChild(input_Text_Alias);
		}
		else if(arrField_Alias_Current[i].IsCategory)
		{
			var select_Text_Alias = document.createElement("select");
			select_Text_Alias.style.width = "145px";
			//<option selected="selected" value="0" id="option_Tool_select_0">Select layer</option>
			var option_Text_Alias = document.createElement("option");
			option_Text_Alias.selected = "selected";
			option_Text_Alias.value = "0";
			option_Text_Alias.id = "option_Map_AddFeature_Attribute_" + arrField_Alias_Current[i].Name + "_none";
			option_Text_Alias.innerText = "<none>";
			
			var option_Text_Alias1 = document.createElement("option");
			option_Text_Alias1.value = "1";
			option_Text_Alias1.id = "option_Map_AddFeature_Attribute_" + arrField_Alias_Current[i].Name + "_1";
			option_Text_Alias1.innerText = "<1>";
			select_Text_Alias.onchange = setChangedComboBox_Attribute;
			select_Text_Alias.appendChild(option_Text_Alias);
			select_Text_Alias.appendChild(option_Text_Alias1);
			
			select_Text_Alias.attribute = arrField_Alias_Current[i].Name;
			if (featureCurrent != null) 
			{
				var objValue = null;
				if (feature_Current_Action.feature) {
					objValue = feature_Current_Action.feature.attributes[arrField_Alias_Current[i].Name];
				} else {
					objValue = feature_Current_Action.attributes[arrField_Alias_Current[i].Name];
				}
				if (objValue != undefined)
				{
					select_Text_Alias[select_Text_Alias.selectedIndex].value = objValue;
				}				
			}
			else
			{
				select_Text_Alias.selectedIndex = 0;
			}
			objTD_Text_Alias.appendChild(select_Text_Alias);
		}
		else
		{
			var input_Text_Alias = document.createElement("input");
			if(arrField_Alias_Current[i].Name.toLowerCase() == "mota") input_Text_Alias = document.createElement("textarea");
			else input_Text_Alias.type = "text";
			input_Text_Alias.style.width = "145px";
			input_Text_Alias.id = "txt_Map_AddFeature_Attribute_" + arrField_Alias_Current[i].Name;
			if (featureCurrent != null) {
				var objValue = null;
				if (feature_Current_Action.feature) {
					objValue = feature_Current_Action.feature.attributes[arrField_Alias_Current[i].Name];
				} else {
					objValue = feature_Current_Action.attributes[arrField_Alias_Current[i].Name];
				}
				if (objValue != undefined)
					input_Text_Alias.value = objValue;
			}
			else
			{
				switch(arrField_Alias_Current[i].Name.toLowerCase())
				{
				case "diachiip":
					input_Text_Alias.value = IP_Addr;
					break;
				case "ngaycapnhat":
					break;
				case "nguoicapnhat":
					break;
				case "quanhuyen":
					if(vectorDistricts!=null)
					{
						var indexLayer = _select_Tool_cboLayers[_select_Tool_cboLayers.selectedIndex].value;
						var bounds_District = feature_Current_Action.geometry.bounds;
						if( Vector_Array[indexLayer - numBaseLayer].Geometry_Type=="point")
						{
							var tolerance = 1;
							bounds_District.left -= tolerance;
							bounds_District.right += tolerance;
							bounds_District.top += tolerance;
							bounds_District.bottom -= tolerance;	
						}
						var ii=0;
						for(ii=0;ii<arrFeature_District.length;ii++)
						{
							var featureDistrict = arrFeature_District[ii];
							var b = featureDistrict.geometry.bounds;
							if (bounds_District.intersectsBounds(b)) {
								input_Text_Alias.value = featureDistrict.attributes["DIST_ID"] + " - " + featureDistrict.attributes["NAME_VN"];
								break;
							}
						}
					}
					break;
				case "phuongxa":
					if(vectorCommune!=null)
					{
						var indexLayer = _select_Tool_cboLayers[_select_Tool_cboLayers.selectedIndex].value;
						var bounds_Commune = feature_Current_Action.geometry.bounds;
						if( Vector_Array[indexLayer - numBaseLayer].Geometry_Type=="point")
						{
							var tolerance = 1;
							bounds_Commune.left -= tolerance;
							bounds_Commune.right += tolerance;
							bounds_Commune.top += tolerance;
							bounds_Commune.bottom -= tolerance;	
						}
						var ii=0;
						for(ii=0;ii<arrFeature_Commune.length;ii++)
						{
							var featureDistrict = arrFeature_Commune[ii];
							var b = featureDistrict.geometry.bounds;
							if (bounds_Commune.intersectsBounds(b)) {
								input_Text_Alias.value = featureDistrict.attributes["COM_ID"] + " - " + featureDistrict.attributes["NAME_VN"];
								break;
							}
						}
					}
					break;
				case "anhminhhoa":
					break;
				}
			}
			input_Text_Alias.attribute = arrField_Alias_Current[i].Name;
			input_Text_Alias.onchange = setChangedText_Attribute;
			if(arrField_Alias_Current[i].Type=="int")
			{
				input_Text_Alias.IsDecimal=0;
				input_Text_Alias.onkeydown = txtKeyDown;
			}
			if(arrField_Alias_Current[i].Type=="decimal")
			{
				input_Text_Alias.IsDecimal=1;
				input_Text_Alias.onkeydown = txtKeyDown;
			}
			objTD_Text_Alias.appendChild(input_Text_Alias);
		}

		objTR_Alias.appendChild(objTD_Title_Alias);
		objTR_Alias.appendChild(objTD_Text_Alias);
		objTable.appendChild(objTR_Alias);
	}

	/*
	 * <tr> <td colspan="2" style="margin: 5px"> <input type="button" value="Add
	 * Feature" onclick="addFeature();" /> </td> </tr>
	 */
	var objTR_Click = document.createElement("tr");
	var objTD_Click = document.createElement("td");
	objTD_Click.colspan = "2";
	var input_Click = document.createElement("input");
	input_Click.type = "button";
	input_Click.id = "btn_Map_AddFeature_Attribute";
	input_Click.value = l_btn_Map_AddFeature;
	input_Click.onclick = addFeature;
	input_Click.style.margin = "5px 0px 5px 3px";
	objTD_Click.appendChild(input_Click);
	objTR_Click.appendChild(objTD_Click);
	objTable.appendChild(objTR_Click);

	_div_Map_divAddFeature_Attribute.appendChild(objTable);
}

// key down textbox
function txtKeyDown(event) {
    // Allow: backspace, delete, tab, escape, and enter
    if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 ||
    // Allow: Ctrl+A
        (event.keyCode == 65 && event.ctrlKey === true) ||
    // Allow: home, end, left, right
        (event.keyCode >= 35 && event.keyCode <= 39)) {
        // let it happen, don't do anything
        return;
    }
    // Allow: .
    else if (event.keyCode == 190) {
        var sText = this.value;
        var isDecimal = this.IsDecimal;
        if ((sText.indexOf('.') == -1) && (isDecimal == 1) && (sText.length>1)) return;
        else event.preventDefault();
    }
    else {
        // Ensure that it is a number and stop the keypress
        if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105)) {
            event.preventDefault();
        }
    }
}

function setChangedText_Attribute() {
	if (feature_Current_Action == null) {
		alert("Feature current null");
		return;
	}
	bSaveEditting = false;
	if (feature_Current_Action.feature) {
		feature_Current_Action.feature.attributes[this.attribute] = this.value;
	} else {
		feature_Current_Action.attributes[this.attribute] = this.value;
	}
}

function setChangedComboBox_Attribute()
{
	if (feature_Current_Action == null) {
		alert("Feature current null");
		return;
	}
	bSaveEditting = false;
	var objValue = this[this.selectedIndex].value;
	if (feature_Current_Action.feature) {
		feature_Current_Action.feature.attributes[this.attribute] = objValue;
	} else {
		feature_Current_Action.attributes[this.attribute] = objValue;
	}
}

function addFeature() {
	// alert("add feature");
	var indexLayer = _select_Tool_cboLayers[_select_Tool_cboLayers.selectedIndex].value;
	if (Action_Current == Portlet_Type_Action.Edit)
		feature_Current_Action.state = OpenLayers.State.UPDATE;
	else if (Action_Current == Portlet_Type_Action.Insert) {
		// add action
		MapAction.Add_Action(true);
		indexLayer = indexLayer - 1 - map_WMS.length;
		Snap_Obj[indexLayer].activate();
	}
	_div_Map_divAddFeature_Attribute.style.display = "none";
	Panel_Current.current_ImgAction.finish = true;
}

function AddFeature_Attribute_Close() {
	var indexLayer = _select_Tool_cboLayers[_select_Tool_cboLayers.selectedIndex].value;
	var layer_Activate = map.layers[indexLayer];
	if (feature_Current_Action != null)
		layer_Activate.drawFeature(feature_Current_Action, "default");
	getAttr("_div_Map_divAddFeature_Attribute", "display:none;");
	if (Action_Current == Portlet_Type_Action.Insert
			|| Action_Current == Portlet_Type_Action.Add_Line_Extension) {
		featureRemove(feature_Current_Action);
		// add action
		MapAction.Add_Action(true);
		indexLayer = indexLayer - 1 - map_WMS.length;
		Snap_Obj[indexLayer].activate();
		Panel_Current.current_ImgAction.finish = true;
	}
	else if (Action_Current == Portlet_Type_Action.Edit)
	{
	}
		
	return false;
}

function AddFeature_Close() {
	var indexLayer = _select_Tool_cboLayers[_select_Tool_cboLayers.selectedIndex].value;
	var layer_Activate = map.layers[indexLayer];
	if (feature_Current_Action != null)
		layer_Activate.drawFeature(feature_Current_Action, "default");
	getAttr("_div_Map_divModifyFeature_Attribute", "display:none;");
	getAttr("_div_Map_divAddFeature", "display:none;");
	Portlet_Panel.setCurrent_ImgAction(panelPortlet,
			panelPortlet.current_ImgAction_Deault);
	Panel_Current.current_ImgAction.finish = true;
	return false;
}
/** *************** END ADD ******************** */

/*******************************************************************************
 * MODIFY **************** OpenLayers.Control.ModifyFeature.RESHAPE = 1;
 * OpenLayers.Control.ModifyFeature.RESIZE = 2;
 * OpenLayers.Control.ModifyFeature.ROTATE = 4;
 * OpenLayers.Control.ModifyFeature.DRAG = 8;
 ******************************************************************************/
var _delta_HeightAttribute = 0;
function clickEvent_ModifyFeature(evt) {
	var indexLayer = _select_Tool_cboLayers[_select_Tool_cboLayers.selectedIndex].value;
	var Coordinate = map.getLonLatFromPixel(evt.xy);
	var tolerance = 50;
	var bounds = new OpenLayers.Bounds(Coordinate.lon - tolerance,
			Coordinate.lat - tolerance, Coordinate.lon + tolerance,
			Coordinate.lat + tolerance);
	var layer_Activate = map.layers[indexLayer];
	var feature = null;
	var i = 0;
	for (i = 0; i < layer_Activate.features.length; i++) {
		var _feature = layer_Activate.features[i];
		var b = _feature.geometry.bounds;
		// neu doi tuong la point
		if (b.left == b.right) {
			b = new OpenLayers.Bounds(b.left - tolerance, b.bottom - tolerance,
					b.right + tolerance, b.top + tolerance);
		}
		if (bounds.intersectsBounds(b)) {
			layer_Activate.drawFeature(_feature, "select");
			feature = _feature;
			break;
		}
	}
	if (feature_Current_Action != null)
		layer_Activate.drawFeature(feature_Current_Action, "default");
	if (feature != null) {
		feature_Current_Action = feature;
		var _txt_Map_FeatureSelected_Modify = _getElementById('txt_Map_FeatureSelected_Modify');
		_txt_Map_FeatureSelected_Modify.value = feature_Current_Action.fid;

		if (arrField_Alias_Current.length == 0) {
			indexLayer = _select_Tool_cboLayers[_select_Tool_cboLayers.selectedIndex].value;
			var sLayerID = Vector_Array[indexLayer - numBaseLayer].LayerId; // tru di lop base layer
			var i = 0;
			for (i = 0; i < arrField_Alias.length; i++) {
				if (trim(arrField_Alias[i].LayerName.toLowerCase()) == trim(sLayerID.toLowerCase())) {
					arrField_Alias_Current[arrField_Alias_Current.length] = arrField_Alias[i];
				}
			}
			arrField_Alias_Current.sort(function(a, b) {
				var x = a.Index - b.Index;
				return x;
			});
		}
		if (arrField_Alias_Current.length == 0) {
			alert("No attribute");
			_div_Map_divAddFeature_Attribute.style.display = "none";
			return;
		}
		if(action_Modify!="attr")
		{
			indexLayer = _select_Tool_cboLayers[_select_Tool_cboLayers.selectedIndex].value;
			indexLayer = indexLayer - 1 - map_WMS.length;
			clickEvent.deactivate();
			Modify_Obj[indexLayer].activate();
			if(action_Modify == "drag") Modify_Obj[indexLayer].mode = OpenLayers.Control.ModifyFeature.DRAG;
			else Modify_Obj[indexLayer].mode = OpenLayers.Control.ModifyFeature.RESHAPE;
			Modify_Obj[indexLayer].selectFeature(feature_Current_Action);
			layer_Activate.drawFeature(feature_Current_Action, "select");
		}
		else 
		{
			// _div_Map_divAddFeature_Attribute
			_div_Map_divAddFeature_Attribute.style.display = "block";
			var top = _div_Map_divToolbar.offsetTop + _div_Map_divToolbar.offsetHeight + _delta_HeightAttribute;
			var left = map_Left + map_Width - _div_Map_divAddFeature_Attribute.offsetWidth;
			_div_Map_divAddFeature_Attribute.style.top = (top + 5) + "px";
			_div_Map_divAddFeature_Attribute.style.left = (left - 5) + "px";
			_div_Map_divAddFeature_Attribute.innerHTML = "";
			fillContructor_from_XML(feature_Current_Action);
		}
	} else {
		// alert("no find feature when select...");
		feature_Current_Action = null;
		var _txt_Map_FeatureSelected_Modify = _getElementById('txt_Map_FeatureSelected_Modify');
		_txt_Map_FeatureSelected_Modify.value = "feature selected is null";
	}
}

function dbclickEvent_ModifyFeature(evt) {
	var indexLayer = _select_Tool_cboLayers[_select_Tool_cboLayers.selectedIndex].value;
	var Coordinate = map.getLonLatFromPixel(evt.xy);
	var tolerance = 50;
	var bounds = new OpenLayers.Bounds(Coordinate.lon - tolerance,
			Coordinate.lat - tolerance, Coordinate.lon + tolerance,
			Coordinate.lat + tolerance);
	var layer_Activate = map.layers[indexLayer];
	var feature = null;
	var i = 0;
	for (i = 0; i < layer_Activate.features.length; i++) {
		feature = layer_Activate.features[i];
		var b = feature.geometry.bounds;
		if (b.left == b.right)
			b = new OpenLayers.Bounds(b.left - tolerance, b.bottom - tolerance,
					b.right + tolerance, b.top + tolerance);
		if (bounds.intersectsBounds(b)) {
			layer_Activate.drawFeature(
					feature_Perpendicular_Parallel_Direction, "select");
			break;
		}
	}
	if (feature_Current_Action != null)
		layer_Activate.drawFeature(feature_Current_Action, "default");
	if (feature != null) {
		feature_Current_Action = feature;
	}
}

var action_Modify="vertex";
function event_ModiyFeature(obj) {
	var indexLayer = _select_Tool_cboLayers[_select_Tool_cboLayers.selectedIndex].value;
	var objModify = obj;
	var layer_Activate = map.layers[indexLayer];
	if (feature_Current_Action != null)
		layer_Activate.drawFeature(feature_Current_Action, "default");
	if (!objModify.checked) {
		// cap nhat lai index cua doi tuong edit - xem giai thich o g_p.js
		indexLayer = indexLayer - 1 - map_WMS.length;
		switch (objModify.value) {
		case 'drag':
			AddFeature_Attribute_Close();
			MapAction.DeActive();
			action_Modify = "drag";
			bSaveEditting = false;
			if(action_Modify != "attr" && feature_Current_Action != null)
			{
				clickEvent.deactivate();
				Modify_Obj[indexLayer].activate();
				Modify_Obj[indexLayer].mode = OpenLayers.Control.ModifyFeature.DRAG;
				Modify_Obj[indexLayer].selectFeature(feature_Current_Action);
				layer_Activate.drawFeature(feature_Current_Action, "select");
			}
			else clickEvent.activate();
			getAttr("_div_Map_divModifyFeature_Attribute", "display:none;");
			break;
		case 'vertex':
			AddFeature_Attribute_Close();
			MapAction.DeActive();
			action_Modify = "vertex";
			bSaveEditting = false;
			if(action_Modify != "attr" & feature_Current_Action != null)
			{
				clickEvent.deactivate();
				Modify_Obj[indexLayer].activate();
				Modify_Obj[indexLayer].mode = OpenLayers.Control.ModifyFeature.RESHAPE;
				Modify_Obj[indexLayer].selectFeature(feature_Current_Action);
				layer_Activate.drawFeature(feature_Current_Action, "select");
			}
			else clickEvent.activate();
			getAttr("_div_Map_divModifyFeature_Attribute", "display:none;");
			break;
		case 'delvertex':
			AddFeature_Attribute_Close();
			MapAction.DelVertice_Action(true);
			action_Modify = "delvertext";
			if(feature_Current_Action != null) 
			{
				DelVertices_Obj[indexLayer].onSelect(feature_Current_Action);
				layer_Activate.drawFeature(feature_Current_Action, "select");
			}
			break;
		case 'attribute':
			MapAction.DeActive();
			action_Modify = "attr";
			if(feature_Current_Action!=null)
			{
				var _txt_Map_FeatureSelected_Modify = _getElementById('txt_Map_FeatureSelected_Modify');
				_txt_Map_FeatureSelected_Modify.value = feature_Current_Action.fid;
	
				// _div_Map_divAddFeature_Attribute
				_div_Map_divAddFeature_Attribute.style.display = "block";
				var top = _div_Map_divToolbar.offsetTop + _div_Map_divToolbar.offsetHeight + _delta_HeightAttribute;
				var left = map_Left + map_Width - _div_Map_divAddFeature_Attribute.offsetWidth;
				_div_Map_divAddFeature_Attribute.style.top = (top + 5) + "px";
				_div_Map_divAddFeature_Attribute.style.left = (left - 5) + "px";
				_div_Map_divAddFeature_Attribute.innerHTML = "";
				if (arrField_Alias_Current.length == 0) {
					indexLayer = _select_Tool_cboLayers[_select_Tool_cboLayers.selectedIndex].value;
					var sLayerID = Vector_Array[indexLayer - numBaseLayer].LayerId; // tru di lop base layer
					var i = 0;
					for (i = 0; i < arrField_Alias.length; i++) {
						if (trim(arrField_Alias[i].LayerName.toLowerCase()) == trim(sLayerID)) {
							arrField_Alias_Current[arrField_Alias_Current.length] = arrField_Alias[i];
						}
					}
					arrField_Alias_Current.sort(function(a, b) {
						var x = a.Index - b.Index;
						return x;
					});
				}
				if (arrField_Alias_Current.length == 0) {
					alert("No attribute");
					_div_Map_divAddFeature_Attribute.style.display = "none";
					return;
				}
				layer_Activate.drawFeature(feature_Current_Action, "select");
				fillContructor_from_XML(feature_Current_Action);
			}
			else clickEvent.activate();
			getAttr("_div_Map_divModifyFeature_Attribute", "display:block;");
			break;
		}
	}
}

function ModifyFeature_Close() {
	var indexLayer = _select_Tool_cboLayers[_select_Tool_cboLayers.selectedIndex].value;
	var layer_Activate = map.layers[indexLayer];
	if (feature_Current_Action != null)
		layer_Activate.drawFeature(feature_Current_Action, "default");
	AddFeature_Attribute_Close();
	getAttr("_div_Map_divModifyFeature", "display:none;");
	Portlet_Panel.setCurrent_ImgAction(panelPortlet, panelPortlet.current_ImgAction_Deault);
	return false;
}
/** *************** END MODIFY ******************** */

/** **************** DELETE VERTICES **************** */
function onModificationStart(feature) {
}

function onModification(feature) {
}

function onModificationEnd(feature) {
}